﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using EzDesk.EzAppApi.Web.Utility.Controllers;
using System.Text;
using EzDesk.EzAppApi.Utility.Models;
using EzDesk.EzAppApi.Web.Utility.Attributes;
using EzDesk.Project.Service;
using EzDesk.EzAppApi.Utility;
using System.IO;
using System.Web.Hosting;
using EzDesk.Project.Model;
using EzDesk.EzAppApi.Utility.EzDeskAppApi;
using EzDesk.Project.Model.ViewModel;
using EzDesk.Project.DesktopWeb.Models;
using System.Web.Script.Serialization;

namespace EzDesk.Project.DesktopWeb.Controllers
{

    public class ProjectController : EzAppController
    {
        private IProjectService _projectService;

        public ProjectController(IEzApiClient apiClient, IProjectService projectService)
        {
            this._apiClient = apiClient;
            this._projectService = projectService;
        }

        public ProjectController()
            : this(new EzApiClient(), new ProjectService())
        {
        }

        #region [ Task ]

        [HttpGet]
        [EzDeskAppSessionAuthorize]
        public ActionResult Task()
        {
            AppTaskCollection taskCollection = new AppTaskCollection();

            // 把现在系统里的项目全部取出来
            var currentProjectList = _projectService.GetProjetList(isClosed: false, orderBy: "CreateOn");

            foreach (var project in currentProjectList)
            {
                taskCollection.AddTask(
                    project.ProjectName,
                    "查看[" + project.ProjectName + "]项目详细信息",
                    string.Format("/project/projectDetail?projectId={0}", project.Id.ToString())
                    );
            }

            taskCollection.AddTask("项目总览", "打开所有项目列表", "/project/projectList");

            taskCollection.AddTask("创建项目", "创建新的项目", "/project/createProject");

            taskCollection.AddTask("添加工作日志/计划", "添加工作日志/计划", "/project/CreateWorkItem");
            taskCollection.AddTask("分配工作任务", "为其他人分配工作任务", "/project/AssignWorkItem");

            taskCollection.AddTask("我的工作日志", "查看我的工作日志和计划", "/project/myWorkItem");
            taskCollection.AddTask("公司工作日志", "查看大家的工作日志和计划", "/project/workItemList");


            return Task(taskCollection);
        }

        #endregion

        [HttpGet]
        [EzDeskAppSessionAuthorize]
        public ActionResult CreateProject()
        {
            // 获取所有项目类型
            ViewData["AllProjectTypes"] = _projectService.GetAllProjectTypes();

            return View();
        }

        [HttpGet]
        [EzDeskAppSessionAuthorize]
        public ActionResult ProjectList()
        {
            IList<ProjectBasicInfo> projectLists = _projectService.GetAllProjects();
            IList<ProjectViewModel> projectForViews = _projectService.GetProjectForView(projectLists);

            IList<PlaneType> planeTypes = _projectService.GetAllPlaneTypes();

            // 直接获取当前系统中所有项目
            ViewData["AllProejcts"] = projectForViews;
            ViewData["PlaneTypes"] = planeTypes;
            return View();
        }



        [HttpGet]
        [EzDeskAppSessionAuthorize]
        public ActionResult ProjectDetail(Guid projectId)
        {
            var basicInfo = _projectService.GetProjectBasicInfo(projectId);

            ViewData["ProjectBasicInfo"] = basicInfo;
            // gantt图
            return View();
        }

        [HttpGet]
        [EzDeskAppSessionAuthorize]
        public ActionResult PlaneTask()
        {
            return View();
        }

        [HttpGet]
        [EzDeskAppSessionAuthorize]
        public ActionResult TaskDetail()
        {
            return View();
        }

        [HttpGet]
        [EzDeskAppSessionAuthorize]
        public ActionResult CreateWorkItem()
        {
            return View();
        }

        [HttpGet]
        [EzDeskAppSessionAuthorize]
        public ActionResult AssignWorkItem()
        {
            return View();
        }

        [HttpGet]
        [EzDeskAppSessionAuthorize]
        public ActionResult MyWorkItem()
        {
            return View();
        }
        [HttpGet]
        [EzDeskAppSessionAuthorize]
        public ActionResult WorkItemDetail()
        {
            return View();
        }



        [HttpGet]
        [EzDeskAppSessionAuthorize]
        public ActionResult TestJson()
        {
            return View();
        }




        #region [ Ajax Methods]

        [HttpGet]
        [EzDeskAppSessionAuthorize]
        public JsonResult GetPlaneTaskDetailJsonView(Guid planeTaskId)
        {
            GanttPlaneTaskModel planeTaskDetail = getPlaneTaskDetailJsonModel(planeTaskId);
            return Json(planeTaskDetail, JsonRequestBehavior.AllowGet);
        }

        [HttpGet]
        [EzDeskAppSessionAuthorize]
        public JsonResult GetProjectDetailJsonView(Guid projectId)
        {
            GanttProjectModel ganttProject = getProjectDetailJsonModel(projectId);
            return Json(ganttProject, JsonRequestBehavior.AllowGet);
        }

        private GanttProjectModel getProjectDetailJsonModel(Guid projectId)
        {
            ProjectBasicInfo projectBasicInfo = _projectService.GetProjectBasicInfo(projectId);
            IList<PlaneTask> planeTasks = _projectService.GetPlanesFromProject(projectId);

            GanttProjectModel ganttProject = new GanttProjectModel(projectBasicInfo);
            List<GanttPlaneTaskModel> ganttPlaneTaskList = new List<GanttPlaneTaskModel>();

            foreach (var planeTask in planeTasks)
            {
                ganttPlaneTaskList.Add
                    (getPlaneTaskDetailJsonModel(planeTask.Id)
                    );
            }

            ganttProject.Planes = ganttPlaneTaskList.ToArray();
            return ganttProject;
        }

        private GanttPlaneTaskModel getPlaneTaskDetailJsonModel(Guid planeTaskId)
        {
            PlaneTask planeTask = _projectService.GetPlaneTask(planeTaskId);
            ProjectBasicInfo project = _projectService.GetProjectBasicInfo(planeTask.ProjectId);
            ProjectTeam team = _projectService.GetProjectTeam(project.ProjectTeamId);

            IList<Task> childTasks = _projectService.GetChildTasks(planeTask);


            GanttPlaneTaskModel planeTaskDetail = new GanttPlaneTaskModel(planeTask);
            planeTaskDetail.TeamMembers = team.Members.ToArray();

            List<GanttTaskModel> childTaskList = new List<GanttTaskModel>();
            foreach (var childTask in childTasks)
            {
                childTaskList.Add(new GanttTaskModel(childTask));
            }
            planeTaskDetail.ChildTasks = childTaskList.ToArray();

            return planeTaskDetail;

        }

        [HttpPost]
        [EzDeskAppSessionAuthorize]
        public JsonResult SaveProjectDetailJsonView()
        {
            string jsonText = Request.Form["jsonData"];

            var projectModelToSave = new JavaScriptSerializer().Deserialize<GanttProjectModel>(jsonText);

            // 遍历所有Task 找出clientAction
            foreach (var planeTask in projectModelToSave.Planes)
            {
                savePlaneChangesFromJsonView(planeTask);
            }

            object 这里要断点 = null;

            EzDeskReturnInfo result = new EzDeskReturnInfo()
            {
                State = "Success",
                Info = "搞定",
            };
            return Json(result);
        }

        private void savePlaneChangesFromJsonView(GanttPlaneTaskModel planeTask)
        {
            var sortedPlaneTaskChanges = planeTask.ChangedTasks.OrderBy(p => p.ClientActionDate);
            foreach (var planeChange in sortedPlaneTaskChanges)
            {
                if (planeChange.ClientAction == "Create")
                {
                    // 创建一个Task
                    // 判断是PlaneTask还是Task
                }
                else if (planeChange.ClientAction == "Delete")
                {
                    // 删除一个Task
                    //_projectService.RemoveTask(planeChange.
                }

            }

            throw new NotImplementedException();
        }

        [HttpPost]
        [EzDeskAppSessionAuthorize]
        public JsonResult CreateProject(FormCollection form)
        {
            // 获取所有项目类型
            string projectName = form["p_projectName"];
            string projectNo = form["p_projectNo"];
            string remark = form["p_remark"];

            ProjectTypeEnum projectType = ProjectTypeEnum.其它;
            if (form["p_projectType"] != null)
            {
                projectType = (ProjectTypeEnum)Enum.Parse(typeof(ProjectTypeEnum), form["p_projectType"]);
            }

            SimpleUser teamManager = null;
            if (form["p_teamLeaderId"] != null)
            {
                teamManager = _apiClient.GetSimpleUserById(new Guid(form["p_teamLeaderId"]));
            }

            IList<SimpleUser> teamMembers = new List<SimpleUser>();
            if (form["p_teamMemberId"] != null)
            {
                teamMembers = _apiClient.GetSimpleUserInfos(form["p_teamMemberId"]);
            }

            ProjectBasicInfo basicInfo = new ProjectBasicInfo()
            {
                ProjectName = projectName,
                ProjectNo = projectNo,
                IsCloesd = false,
                CreateOn = DateTime.Now,
                Remark = remark,
                Creator = CurrentSimpleUserInfo,
                ProjectType = projectType,
            };

            ProjectTeam teamInfo = new ProjectTeam()
            {
                Manager = teamManager,
                Members = teamMembers,
            };

            EzDeskReturnInfo result = new EzDeskReturnInfo();
            result.State = "Success";

            try
            {
                var newProjectId = _projectService.CreateProject(basicInfo, teamInfo, CurrentSimpleUserInfo);
                result.Data = new { ProjectId = newProjectId };
                result.Info = string.Format("项目“{0}”创建成功", projectName);
            }
            catch (Exception ex)
            {
                result.State = "Error";
                result.Info = ex.Message;
            }

            return Json(result);
        }

        [HttpPost]
        [EzDeskAppSessionAuthorize]
        public JsonResult CreatePlaneTask(FormCollection form)
        {
            Guid projectId = Guid.Empty;
            if (form["p_projectId"] != null)
            {
                projectId = new Guid(form["p_projectId"]);
            }

            PlaneTypeEnum planeType = PlaneTypeEnum.方案;
            if (form["p_planeType"] != null)
            {
                planeType = (PlaneTypeEnum)Enum.Parse(typeof(PlaneTypeEnum), form["p_planeType"]);
            }

            DateTime startOn = new DateTime();
            DateTime.TryParse(form["p_startOn"], out startOn);

            DateTime endOn = new DateTime();
            DateTime.TryParse(form["p_endOn"], out endOn);

            Guid planeDirectorId = Guid.Empty;
            if (form["p_directorId"] != null)
            {
                planeDirectorId = new Guid(form["p_directorId"]);
            }

            EzDeskReturnInfo result = new EzDeskReturnInfo();
            try
            {
                PlaneTask newPlaneTask = new PlaneTask()
                {
                    Id = Guid.NewGuid(),
                    ProjectId = projectId,
                    StartOn = startOn,
                    EndOn = endOn,
                    IsClosed = false,
                    PlaneType = planeType,
                    Director = new SimpleUser() { Id = planeDirectorId },
                    Description = "", //todo:....没这个属性
                };

                _projectService.CreatePlaneTask(newPlaneTask);

                result.State = "Success";
                result.Info = "新阶段任务已创建";
                result.Data = new { Id = newPlaneTask.Id, ProjectId = newPlaneTask.ProjectId };
            }
            catch (Exception ex)
            {
                result.State = "Error";
                result.Info = ex.Message;
            }
            return Json(result);
        }

        [HttpGet]
        [EzDeskAppSessionAuthorize]
        public JsonResult GetTeamMembers(Guid teamId)
        {
            return Json(_projectService.GetProjectTeam(teamId), JsonRequestBehavior.AllowGet);
        }



        [HttpGet]
        [EzDeskAppSessionAuthorize]
        public ActionResult PlaneTaskItemInList(Guid planeTaskId)
        {
            var viewModel = _projectService.GetPlaneTaskForView(planeTaskId);
            return View(viewModel);
        }


        [HttpPost]
        [EzDeskAppSessionAuthorize]
        public ActionResult TestUpdateJson()
        {
            var x = 0;
            return null;
        }
        #endregion
    }
}
